<?php

namespace app\admin\controller\sales;

use app\common\controller\Backend;
use app\common\model\customer\Customer;
use app\common\model\goods\Goods;
use app\common\model\sales\ChangeGoods;
use app\common\model\sales\CheckoutGoods;
use think\Db;
use app\common\model\goods\GoodsHouseStock;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Change extends Backend
{
    
    /**
     * Change模型对象
     * @var \app\common\model\sales\Change
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\sales\Change();

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['salescheckout','salesslip','customer','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['salescheckout','salesslip','customer','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','explain','abstract','operator','company','status','tax','th_status','fh_status']);
                $row->visible(['salescheckout']);
				$row->getRelation('salescheckout')->visible(['number']);
				$row->visible(['salesslip']);
				$row->getRelation('salesslip')->visible(['number']);
				$row->visible(['customer']);
				$row->getRelation('customer')->visible(['company']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();

            $statuss = $this->model->change_status();
//            $thstatus = $this->model->th_status();
//            $fhstatus = $this->model->fh_status();
            foreach ($list as $k=> $v){
                $list[$k]['ystatus'] = $v['status'];
//                $list[$k]['yth_status'] = $v['th_status'];
//                $list[$k]['yfh_status'] = $v['fh_status'];
                $list[$k]['status'] = $statuss[$v['status']];
//                $list[$k]['th_status'] = $thstatus[$v['th_status']];
//                $list[$k]['fh_status'] = $fhstatus[$v['fh_status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids=null){

        if ($this->request->isAjax()){

            $status = input('status/d',0);
            if(empty($status)){
                $this->error('状态异常');
            }
            $row = $this->model->find($ids);
            if(!$row){
                $this->error('订单不存在');
            }
            if($row['status'] !=1){
                $this->error('订单状态异常');
            }
            Db::startTrans();
            try {
                if($status == 2){
                    $odata['status'] = $status;

                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    $custrow = Customer::find($row['customer_id']);

                    $custrow = Customer::find($row['customer_id']);
                    if($row['actual_cost'] >0){//收入
                        $is_income = 1;
                    }else if($row['actual_cost'] <0){ //支出
                        $is_income = 2;
                    }else{
                        $is_income = 0;
                    }
                    if($is_income >0) {
                            $ress = Db::name('analysis')->insert(array(
                                'is_income' => 1,
                                'source' => 8,
                                'cost' => $row['actual_cost'],
                                'admin_id' => $row['admin_id'],
                                'group_id' => $row['group_id'],
                                'company' => $row['company'],
                                'operator' => $row['operator'],
                                'source_id' => $row['id'],
                                'obj_id' => $row['customer_id'],
                                'storehouse_id' => $row['storehouse_id'],
                                'controller' => 'sales/change',
                                'settle_name' => $custrow['company'],
                                'number' => $row['number'],
                                'createtime' => time(),
                                'explain' => $row['explain'],//摘要
                            ));
                            if(!$ress){
                                throw new Exception('数据异常');
                            }
                    }

                    $type = 1;
                }else{//驳回
                    $odata['status'] = $status;
                    $type = 2;
                    Db::name('sales_change_goods')->where(array('sales_change_id'=>$ids))->update(array('status'=>0));
                }
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'sales/change',
                    'source_id'=>$ids,
                    'source'=>8,
                    'remark'=>'销售换货单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));
                $res = $this->model->save($odata,array('id'=>$ids));
                if($res){
                    Db::commit();
                    return  array(
                        'code'=>1,
                        'msg'=>'审核成功',
                    );
                }else{
                    throw new Exception('审核失败');
                }
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);

        $list = Db::name('sales_change_goods')
            ->field('g.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,sg.goods_type,storehouse_id,costPrice,sfhj')
            ->alias('sg')
            ->where(array('sales_change_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        foreach ($list as $k => $v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],$v['storehouse_id']);
        }
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('is_finance',input('is_finance/d',0));
        $this->assign('list',$list);
        $this->assign('row',$row);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    //换货单退货处理 3
    public function thexamine($ids = null){
        $status = input('status/d',0);
        if($status == 3 || $status == 6) {
//            $msg = input('msg/d', 0);
//            if (empty($msg)) {
//                $this->error('内容不能为空');
//            }
            if (empty($status)) {
                $this->error('状态异常');
            }
            $row = $this->model->find($ids);
            if (!$row) {
                $this->error('订单不存在');
            }

            if ($status == 3) {
                $odata['status'] = $status;
//                $msg = input('msg/s', '');
//                if (empty($msg)) {
//                    $this->error('备注信息不能为空');
//                }
            } else {
                $odata['status'] = $status;
            }
            $res = $this->model->save($odata, array('id' => $ids));
//        $sql = Db::table('zax_purchase_order')->getLastSql();
            if ($res) {
                $this->success('审核成功');
            } else {
                $this->error('审核失败');
            }
        }
        $this->error('异常状态');
    }
    //换货单发货处理
    public function fhexamine($ids = null){
        $status = input('status/d',0);
        if($status <=3 || $status >= 6){
            $this->error('异常状态');
        }
        if(empty($status)){
            $this->error('状态异常');
        }
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('订单不存在');
        }


        if($status == 1){
            $odata['status'] = 2;
        }else{
            $odata['status'] = $status;
        }
        Db::startTrans();
        try {
            if ($odata['status'] == 4) {//到货 加库存 进进销存
                $changsgoods = new ChangeGoods();
                $list = $changsgoods->where(array('sales_change_id' => $ids,'goods_type'=>1))->select();
                if (empty($list)) {
                    $this->error('异常错误');
                }
                foreach ($list as $v) {
                    //修改商品状态
                    $changsgoods = new ChangeGoods();
                    $changsgoods->save(array('status'=>2),array('id'=>$v['id']));

                    //减增加存 根据当时的价格来增加库存价值
                    $GoodsHouseStock = new GoodsHouseStock();
                    $rr = $GoodsHouseStock->addstock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],$v['costPrice'],1);
                    if(!$rr){
                        throw new Exception('库存计算错误');
                    }

//                    $goods = new \app\common\model\goods\Goods();
//                    $final_cost = $goods->getcost($v['goods_id'],$row['storehouse_id']);
//                    $GoodsHouseStock = new GoodsHouseStock;
//                    $stock = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);

                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售换货单',
                        'source'=>8,
                        'type_id'=>$row['id'],
                        'enter_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock']-$v['goods_num'],
                        'now_num'=>$hgood['stock'],
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/change',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
//                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                        'final_cost'=>$v['costPrice'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>$v['costPrice']*$v['goods_num'], //记录的金额应该是入库的采购成本
                        'balance'=>$hgood['balance'], //记录的金额当前库存总额
                    ));
                }
            }
            if($odata['status'] == 5){


                $changsgoods = new ChangeGoods();
                $list = $changsgoods->where(array('sales_change_id' => $ids,'goods_type'=>2))->select();
                if (empty($list)) {
                    $this->error('异常错误');
                }
                foreach ($list as $v) {
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                    if($hgood['stock'] == 0){
                        throw new Exception('库存为0');
                    }



                    if($hgood['stock'] == $v['goods_num']){
                        $balance = 0;
                    }else{
                        $balance = $hgood['balance']-($hgood['balance']/$hgood['stock'])*$v['goods_num'];
                    }

                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售换货单',
                        'source'=>8,
                        'type_id'=>$row['id'],
//                        'enter_num'=>$v['goods_num'],
                            'out_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock'],
                        'now_num'=>$hgood['stock']-$v['goods_num'],
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/change',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
//                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>($hgood['balance']/$hgood['stock'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                        'balance'=>$balance, //记录的金额当前库存总额
                    ));
                    //减少库存
                    $goodshouse = new GoodsHouseStock();
                    $rr = $goodshouse->reducestock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);
                    if (!$rr) {
                        $Goods = new Goods;
                        $ginfo = $Goods->find($v['goods_id']);
                        Db::rollback();
                        throw new Exception($ginfo['title'] . '库存异常,请检查');
                    }

                    //修改商品状态
                    $changsgoods = new ChangeGoods();
                    $changsgoods->save(array('status'=>2,'costPrice'=>$hgood['balance']/$hgood['stock']),array('id'=>$v['id']));
                }
            }

            $res = $this->model->save($odata, array('id' => $ids));
//        $sql = Db::table('zax_purchase_order')->getLastSql();
            if ($res) {
                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }
            throw new Exception('审核失败');
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    public function cancelbill($ids = null){
        if (!$this->request->isAjax()) {
            $this->error('非法操作');
        }
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        $row = $this->model->find($ids);
        if($row['status'] == 1 || $row['status'] >6){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>8,
            'source_id' => $row['id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->find();
        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }
        Db::startTrans();
        try {
            //修改订单
            $this->model->save(array('status'=>8),array('id'=>$ids));
            //修改所有商品状态
            Db::name('sales_change_goods')->where(array('sales_change_id'=>$ids))->update(array('status'=>0));

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

            if($row['status'] == 4){//待发货  收到客户退货 需要 减少库存
                $this->cancel1($row,$ids,$group);
            }
            if($row['status'] == 5 || $row['status'] == 6){//发货中  收到客户退货 并且发货了 需要减少 和增加
                $this->cancel1($row,$ids,$group);
                $this->cancel2($row,$ids,$group);
            }
            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 8,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'sales/change',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));


            //中止记录
            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'sales/change',
                'source_id'=>$ids,
                'source'=>8,
                'remark'=>'销售换货单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            //财务单据作废
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }

            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    protected function  cancel1($row,$ids,$group){
        $changsgoods = new ChangeGoods();
        $list = $changsgoods->where(array('sales_change_id' => $ids,'goods_type'=>1))->select();
        if (empty($list)) {
            throw new Exception('数据异常');
        }
        foreach ($list as $v) {
            $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
            if($hgood['stock'] == 0){
                throw new Exception('库存为0');
            }


            if($hgood['stock'] == $v['goods_num']){
                $balance = 0;
            }else{
                $balance = $hgood['balance']-$v['costPrice']*$v['goods_num'];
            }

            Db::name('goods_stock_log')->insert(array(
                'goods_id'=>$v['goods_id'],
                'createtime'=>time(),
                'number'=>$row['number'],
                'type'=>'销售换货单',
                'source'=>8,
                'type_id'=>$row['id'],
//                'enter_num'=>$v['goods_num'],
                'out_num'=>$v['goods_num'],
                'before_num'=>$hgood['stock'],
                'now_num'=>$hgood['stock']-$v['goods_num'],
                'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                'controller'=>'sales/change',
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
//                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                'final_cost'=>$v['costPrice'], //记录的金额应该是入库的加权单价
                'bill_cost'=>$v['costPrice']*$v['goods_num'], //记录的金额应该是入库的采购成本
                'balance'=>$balance, //记录的金额当前库存总额
                'is_cancel'=>1,
            ));

            //减增加存 根据当时的价格来增加库存价值
            $GoodsHouseStock = new GoodsHouseStock();
            $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],$v['costPrice']);
            if(!$rr){
                throw new Exception('库存计算错误');
            }
        }
    }
    protected function  cancel2($row,$ids,$group)
    {

        $changsgoods = new ChangeGoods();
        $list = $changsgoods->where(array('sales_change_id' => $ids, 'goods_type' => 2))->select();
        if (empty($list)) {
            throw new Exception('异常错误');
        }
        foreach ($list as $v) {
            //增加库存
            $goodshouse = new GoodsHouseStock();
            $rr = $goodshouse->addstock($v['goods_id'], $row['storehouse_id'], $v['goods_num'],$v['costPrice'],1);
            if (!$rr) {
                $Goods = new Goods;
                $ginfo = $Goods->find($v['goods_id']);
//                Db::rollback();
                throw new Exception($ginfo['title'] . '库存异常,请检查');
            }
            $hgood = Db::name('goods_house_stock')->where(array('goods_id' => $v['goods_id'], 'storehouse_id' => $row['storehouse_id']))->find();


            Db::name('goods_stock_log')->insert(array(
                'goods_id' => $v['goods_id'],
                'createtime' => time(),
                'number' => $row['number'],
                'type' => '销售换货单',
                'source'=>8,
                'type_id' => $row['id'],
                'enter_num'=>$v['goods_num'],
//                'out_num' => $v['goods_num'],
                'before_num' => $hgood['stock'] - $v['goods_num'],
                'now_num' => $hgood['stock'],
                'storehouse_id' => $row['storehouse_id'],
                'controller' => 'sales/change',
                'admin_id' => session('admin')['id'],
                'group_id' => $group['group_id'],
                'company' => $group['name'],
                'operator' => session('admin')['nickname'],
                'final_cost' => $v['costPrice'], //记录的金额应该是入库的加权单价
                'bill_cost' => $v['costPrice'] * $v['goods_num'], //记录的金额应该是入库的采购成本
                'balance' => $hgood['balance'], //记录的金额当前库存总额
                'is_cancel'=>1,
            ));
        }
    }
}
